<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    public function __construct()
    {
        //$this->middleware(['ckadmin:login']);
    }
    //登录显示
    public function index()
    {
        //判断用户是否已经登陆过
        if(auth()->check()){
            //跳转到后页
            return redirect(route('admin.index'));
        }
        return view('admin.login.login');
    }
    //登录别名 admin.login 根据别名生成 url route(别名);
    public function login(Request $request)
    {

        //表单验证
        $post = $this->validate($request,[
            'username' => 'required',
            'password' => 'required'
            ],[
                'username.required' => '账号都不写---what are you doing?'
        ]);

        //登录
        $bool = auth()->attempt($post);
        //判断是否登录成功
        if($bool){

            //登录成功
            //得到它的权限
            //判断一下是否是超级管理员
            if(config('rbac.super') != $post['username']) {
                $userModel = auth()->user();
                $roleModel = $userModel->role;
                $nodeArr = $roleModel->nodes()->pluck('route_name', 'id')->toArray();
                //权限保持到session中
                session(['admin.auth' => $nodeArr]);
            }else{
                session(['admin.auth' => true]);
            }

            //return "跳转到后页"
            return redirect(route('admin.index'));
        }
        return redirect(route('admin.login'))->withErrors(['error'=>'登录失败']);

    }


}
